/*
 * @Author: 徐博
 * @Date: 2023-03-20 17:45:31
 * @Last Modified by: 徐博
 * @Last Modified time: 2023-03-20 17:48:41
 */

<template>
    <a-form ref="formRef" name="custom-validation" :model="formState" :rules="rules" v-bind="layout" @finish="handleFinish"
        @validate="validate" @finishFailed="handleFinishFailed">
      <template v-for="item in searchConfigs">
        <a-form-item :name="item.name" :label="itemLabel(item)">
          <a-input v-if="item.type == 'input'" v-model:value="formState[`${item.name}`]"
                   :placeholder="item?.placeholder || t('pleaseInput')"></a-input>
          <a-select v-if="item.type == 'select'" v-model:value="formState[`${item.name}`]" :placeholder="t('pleaseInput')">
            <template v-for="item1 in item.options" :key="item1.value">
              <a-select-option :value="item1.value">{{ item1.name }}</a-select-option>
            </template>
          </a-select>
          <a-range-picker v-if="item.type == 'rangeDatePicker'" v-model:value="formState[`${item.name}`]"
                          :value-format="item.format ? item.format : 'YYYY-MM-DD'" :placeholder="['开始时间', '结束时间']" />
          <a-date-picker v-if="item.type == 'datePicker'" v-model:value="formState[`${item.name}`]"
                         :value-format="item.format ? item.format : 'YYYY-MM-DD'" placeholder="请选择日期" />
        </a-form-item>
      </template>
    </a-form>
</template>

<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form';
import type { FormInstance } from 'ant-design-vue';
import {ref, reactive, defineProps, defineEmits, onMounted, unref} from 'vue';
import {FormActionType, FormSchema} from "@/components/fe-form/fe-form.type";
import {useI18n} from "vue-i18n";

const {t} = useI18n();

interface Props {
  searchConfigs:Array<FormSchema>;
  formState: any;
  labelWidth?: number;
}
const props = withDefaults(defineProps<Props>(), {
  labelWidth: 90,
})
const emits = defineEmits(['register'])
const formRef = ref<FormInstance>()
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
};
const formState = reactive({})
const rules: Record<string, Rule[]> = {}

const itemLabel = (item: any) => {
  return t(item.label)
}

const handleFinish = (values: any) => {
    console.log("values", values)
}
const handleFinishFailed = (err: any) => {
    console.log('err', err)
}
const validate = async(...args: any) => {
  const valid = await unref(formRef)?.validate();
  if (valid) {
    return Promise.resolve(props.formState);
  } else {
    return Promise.reject(false);
  }
}

const getFieldsValue = () => {
  return props.formState;
}

const resetFields = async () => {
  await unref(formRef)?.resetFields();
}

const updateSchema = () => {}

const formActionType: Partial<FormActionType> = {
  getFieldsValue,
  resetFields,
  validate,
};

onMounted(()=> {
  emits('register', formActionType)
})

</script>
